package com.orderplus.opshop.common.util;

import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 用于http请求的工具类
 *
 * @author 何霖
 * @ClassName: HttpUtil
 * @Description: TODO
 * @date 2016年1月15日 上午10:27:49
 */
public final class HttpUtil {
	private static CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();

	private static int TIMEOUT_IN_MILLIONS = 3000;

	// 禁止实例化和继承
	private HttpUtil() {

	}

	private static String getUrl(String url, Map<String, String> params) {
		StringBuilder requestUrl = new StringBuilder(url);
		int i = 0;
		for (Entry<String, String> entry : params.entrySet()) {
			if (entry.getValue() == null || "".equals(entry.getValue())) {
				continue;
			}
			if (i == 0) {
				if (url.matches(".*\\?.*")) {
					requestUrl.append("&");
				} else {
					requestUrl.append("?");
				}
				requestUrl.append(entry.getKey()).append("=").append(entry.getValue());
			} else {
				requestUrl.append("&").append(entry.getKey()).append("=").append(entry.getValue());
			}
			i++;
		}
		//			return URLEncoder.encode(requestUrl.toString(),"UTF-8");
		return requestUrl.toString();
	}


	// 直接页面输出字符串
	public static void setResponse(HttpServletResponse response, Map<String, Object> result) {
		String contentType = "text/html; charset=utf-8";
		if (result.containsKey("contentType")) {
			if (((String) result.get("contentType")).toLowerCase().equals("json")) {
				contentType = "application/json;charset=utf-8";
			}
		}
		response.setContentType(contentType);

		Writer out;
		try {
			out = response.getWriter();
			out.write((String) result.get("content"));
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void setResponse(HttpServletResponse response, String content) {
		setResponse(response, content, "text/html; charset=utf-8");
	}

	public static void setResponse(HttpServletResponse response, String content, String contentType) {
		Map<String, Object> result = new ConcurrentHashMap<>();
		result.put("content", content);
		result.put("contentType", contentType);
		setResponse(response, result);
	}

	/**
	 * 将所有请求参数的值转小写
	 *
	 * @param paramMap
	 * @return
	 */
	public static Map<String, Object> convertKeyToLower(Map<String, String[]> paramMap) {
		Map<String, Object> params = new ConcurrentHashMap<>();
		for (String key : paramMap.keySet()) {
			params.put(key.toLowerCase(), ((String[]) paramMap.get(key))[0]);
		}
		return params;
	}

	/**
	 * 判断请求的来源IP是否为局域网IP
	 * 10.0.0.0~10.255.255.255
	 * 172.16.0.0~172.31.255.255
	 * 192.168.0.0~192.168.255.255
	 *
	 * @param ipAddress
	 * @return
	 */
	public static boolean isIPAllow(String ipAddress) {
		if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
			return true;
		}

		try {
			String reg = "(10|172|192)\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})";
			java.util.regex.Pattern p = java.util.regex.Pattern.compile(reg);
			java.util.regex.Matcher matcher = p.matcher(ipAddress);
			return matcher.find();
		} catch (Exception e) {
		}
		return true;
	}


	public static void setHost(HttpServletRequest request, Map<String, Object> root) {
		String requestUrl = request.getRequestURL().toString().split("\\?")[0].split("//")[1].split("/")[0];

		root.put("host", requestUrl.split(":")[0]);
		if (requestUrl.indexOf(":") >= 0) {
			root.put("port", requestUrl.split(":")[1]);
		} else {
			root.put("port", "80");
		}
	}

	public static Map<String, String> getCookiesMap(HttpServletRequest request) {
		Map<String, String> cookieMap = new ConcurrentHashMap<>();

		for (Cookie cookie : request.getCookies()) {
			cookieMap.put(cookie.getName().toLowerCase(), cookie.getValue());
		}

		return cookieMap;
	}

	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	public static void setResponseJsonString(HttpServletResponse response, String jsonString) {
		String contentType = contentType = "application/json;charset=utf-8";
		response.setContentType(contentType);
		java.io.Writer out;
		try {
			out = response.getWriter();
			out.write(jsonString);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/***
	 * 获取请求的请求参数
	 * @param request
	 * @return
	 */
	public static Map<String, String> getRequestParameters(HttpServletRequest request) {
		Map<String, String> params = new HashMap<>();
		Map<String, String[]> map = request.getParameterMap();
		if (request.getMethod().equals("POST") && request.getContentType() != null && request.getContentType().contains("multipart/form-data")) {
			MultipartHttpServletRequest multiRequest = multipartResolver.resolveMultipart(request);
			map = multiRequest.getParameterMap();
		}
		//将请求参数存入模板变量
		for (String key : map.keySet()) {
			params.put(key, ((String[]) map.get(key))[0]);
		}
		return params;
	}

	/**
	 * 接口返回json格式字符串
	 *
	 * @param response
	 * @param code
	 * @param msg
	 * @param resultData
	 */
	public static void setApiResponse(HttpServletResponse response, Integer code, String msg, Object resultData) {
		Map<String, Object> result = new HashMap();
		result.put("code", code);
		result.put("msg", msg);
		if (resultData != null) {
			result.put("data", resultData);
		}
		String resultJson = JSONUitl.obj2String(result);
		response.setContentType("application/json;charset=utf-8");
		java.io.Writer out;
		try {
			out = response.getWriter();
			out.write(resultJson);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
	}

}
